﻿// Copyright 2009 Mike Geise
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Falcon.Core.Authentication
{
	using System.Collections.Generic;
	using System.Security.Principal;
	using Falcon.Core.Authorization;
	using Falcon.Core.Domain.Enums;

	public abstract class PermissivePrincipal : IPrincipal
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="PermissivePrincipal"/> class.
		/// </summary>
		/// <param name="identity">The identity.</param>
		protected PermissivePrincipal(IIdentity identity)
		{
			this.Identity = identity;
			this.RolePermissions = new Dictionary<string, IdentityPermission>();
		}

		/// <summary>
		/// Determines whether the current principal belongs to the specified role.
		/// </summary>
		/// <param name="role">The name of the role for which to check membership.</param>
		/// <returns>
		/// true if the current principal is a member of the specified role; otherwise, false.
		/// </returns>
		public bool IsInRole(string role)
		{
			if (!this.RolePermissions.ContainsKey(role))
			{
				return false;
			}

			var perm = this.RolePermissions[role];

			return perm.AllowedTo(UserPermissionActions.View);
		}

		/// <summary>
		/// Determines if the instance is allowed to perform a action.
		/// </summary>
		/// <param name="role">The role.</param>
		/// <param name="action">The action.</param>
		/// <returns></returns>
		public bool AllowedTo(string role, UserPermissionActions action)
		{
			if (!this.RolePermissions.ContainsKey(role))
			{
				return false;
			}

			var perm = this.RolePermissions[role];

			return perm.AllowedTo(action);
		}

		/// <summary>
		/// Gets or sets the role permissions.
		/// </summary>
		/// <value>The role permissions.</value>
		protected Dictionary<string, IdentityPermission> RolePermissions
		{
			get;
			private set;
		}

		/// <summary>
		/// Gets the identity of the current principal.
		/// </summary>
		/// <value></value>
		/// <returns>
		/// The <see cref="T:System.Security.Principal.IIdentity"/> object associated with the current principal.
		/// </returns>
		public IIdentity Identity
		{
			get;
			protected set;
		}

		/// <summary>
		/// Determines the role permissions.
		/// </summary>
		public abstract void DetermineRolePermissions();
	}
}